package com.example.apidocserver.infrastructure.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;
import java.io.PrintWriter;

/**
 * 登录配置
 *
 * @author xyqlg
 */
@Configuration
@Slf4j
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    CustomFilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;
    @Resource
    CustomUrlDecisionManager customUrlDecisionManager;

    @Resource
    private UserServiceImpl userService;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService);
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/web/css/**", "/web/js/**", "/web/static/css/**",
                "/web/index.html", "/web/wheat.webp", "/images/**", "/druid/*");
    }

    @Bean
    public LoginFilter loginFilter() throws Exception {
        LoginFilter loginFilter = new LoginFilter();
        // 认证成功
        loginFilter.setAuthenticationSuccessHandler((request, response, authentication) -> {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            UserDetailsImpl principal = (UserDetailsImpl) authentication.getPrincipal();
            log.info("principal.getClass(): {}, pw: {}", principal.getClass(), principal.getPassword());
            out.write(new ObjectMapper().writeValueAsString("登录成功。"));
            out.flush();
            out.close();
        });

        // 认证失败
        loginFilter.setAuthenticationFailureHandler((request, response, exception) -> {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            String result = exception instanceof LockedException ? "账户被锁定!"
                    : exception instanceof CredentialsExpiredException ? "密码过期!"
                    : exception instanceof AccountExpiredException ? "账户过期!"
                    : exception instanceof DisabledException ? "账户被禁用!"
                    : "用户名或者密码输入错误!";
            response.setStatus(HttpStatus.FORBIDDEN.value());
            out.write(new ObjectMapper().writeValueAsString(result));
            out.flush();
            out.close();
        });

        loginFilter.setAuthenticationManager(authenticationManagerBean());
        loginFilter.setFilterProcessesUrl("/login");
        return loginFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().authenticationEntryPoint((req, resp, authException) -> {
            String message = authException.getMessage();
            log.error("req.getRequestURI() = {}, message = {}", req.getRequestURI(), message);
            resp.setContentType("application/json;charset=utf-8");
            resp.setStatus(HttpStatus.FORBIDDEN.value());
            PrintWriter out = resp.getWriter();
            out.write(new ObjectMapper().writeValueAsString("未登录。"));
            out.flush();
            out.close();
        });

        http.csrf().disable();
        //        http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());

        http.antMatcher("/**").authorizeHttpRequests().anyRequest().authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setAccessDecisionManager(customUrlDecisionManager);
                        object.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);
                        return object;
                    }
                });

        http.logout().logoutSuccessHandler((req, resp, authentication) -> {
                    resp.setContentType("application/json;charset=utf-8");
                    PrintWriter out = resp.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("注销成功!"));
                    out.flush();
                    out.close();
                }
        );

        http.addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class);
    }
}
